package net.xo68.destiny.core.serialize;

import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.contract.common.SystemConstants;
import net.xo68.destiny.contract.domain.report.DatagramSerializationException;
import net.xo68.destiny.contract.domain.report.DatagramSerializer;
import net.xo68.destiny.core.json.JsonMapper;
import net.xo68.destiny.core.util.Base64Utils;
import org.apache.commons.lang3.StringUtils;

/**
 * Json结构报文序列化实现
 * @author wuxie
 * @version 2020-12-29
 */
@Slf4j
public class JsonDatagramSerializer implements DatagramSerializer {

    private final JsonMapper jsonMapper;

    public JsonDatagramSerializer(JsonMapper jsonMapper) {
        this.jsonMapper = jsonMapper;
    }

    @Override
    public <T> String serialize(T t) throws DatagramSerializationException {
        if (t == null) {
            return SystemConstants.STRING_EMPTY;
        }

        String jsonStr = jsonMapper.toString(t,false);
        if(StringUtils.isBlank(jsonStr)){
            return SystemConstants.STRING_EMPTY;
        }
        return Base64Utils.encodeFromString(jsonStr);
    }

    @Override
    public String decode(String encodeStr)  throws DatagramSerializationException{
        if(StringUtils.isBlank(encodeStr)){
            return SystemConstants.STRING_EMPTY;
        }
        try {
            String jsonStr=Base64Utils.decodeToString(encodeStr);
            if (StringUtils.isBlank(jsonStr)) {
                return SystemConstants.STRING_EMPTY;
            }
            return jsonStr;
        } catch (Exception ex) {
            throw new DatagramSerializationException("Could not read JSON: " + ex.getMessage(), ex);
        }
    }

    @Override
    public <T> T deserialize(String decodeStr, Class<T> clazz) throws DatagramSerializationException {
        if(StringUtils.isBlank(decodeStr)){
            return null;
        }
        try {
            return jsonMapper.parse(decodeStr,clazz);
        } catch (Exception ex) {
            throw new DatagramSerializationException("Could not read JSON: " + ex.getMessage(), ex);
        }
    }
}
